package com.nclg.exam.controller;

import com.nclg.exam.dto.UpdatePwdDto;
import com.nclg.exam.dto.UpdateUserDto;
import com.nclg.exam.entity.TUser;
import com.nclg.exam.service.UserService;
import com.nclg.exam.utils.JsonResult;
import com.nclg.exam.utils.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 判断用户名是否存在
     * @param uAccount
     * @return
     */
    @GetMapping("/selectAccountExists/{uAccount}")
    public JsonResult selectAccountExists(@PathVariable String uAccount){
        TUser user = userService.selectByAccount(uAccount);
        if (null != user) return JsonResult.failure("用户名已存在");
        return JsonResult.success();
    }

    /**
     * 修改密码
     * @param pwdDto
     * @return
     */
    @PutMapping("/updatePwd")
    public JsonResult updatePwd(@Valid UpdatePwdDto pwdDto){
        TUser user = userService.selectByPrimaryKey(pwdDto.getUId());
        if (null == user) return JsonResult.failure("用户不存在");

        //校验原密码
        boolean isTrue = MD5Utils.checkPwd(pwdDto.getOldPwd(), user.getUPassword(), user.getUSalt());
        if (!isTrue) return JsonResult.failure("原密码错误");

        String newPwd = MD5Utils.encrypt(pwdDto.getNewPwd(), user.getUSalt());
        if (userService.updatePwd(pwdDto.getUId(), newPwd)) {
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            return JsonResult.success("修改成功");
        }

        return JsonResult.failure("修改失败");
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public JsonResult upload(MultipartFile file){
        //判断是否上传了文件
        if (!file.isEmpty()){
            if (file.getOriginalFilename() != ""){
                //获取到上传的文件名
                String filename = file.getOriginalFilename();
                //保存到数据库的文件夹路径
                String path = "/static/images/ico/";
                //指定文件保存的文件夹
                String realPath = "src/main/resources/static" + path;
                //构建目标文件对象
                File f = new File(realPath);
                //如果父目录不存在，则创建该目录
                if (!f.getParentFile().exists()){
                    f.getParentFile().mkdirs();
                }
                //将上传的文件内容写入一个文件
                try {
                    File realFile = new File(f.getAbsolutePath() + File.separator + filename);
                    file.transferTo(realFile);
                    Map<String, Object> res = new HashMap<>();
                    res.put("url", path+filename);
                    return JsonResult.success("上传成功",res);
                } catch (IOException e) {
                    e.printStackTrace();
                    return JsonResult.failure("上传失败");
                }
            }
        }
        return JsonResult.failure("未上传文件");
    }

    /**
     * 修改个人信息
     * @param dto
     * @return
     */
    @PutMapping("/update")
    public JsonResult update(@Valid UpdateUserDto dto, HttpServletRequest request){
        boolean isTrue = userService.updateByPrimaryKeySelective(dto);
        if (!isTrue) return JsonResult.failure("修改失败");
        TUser user = userService.selectByPrimaryKey(dto.getUId());
        request.getSession().setAttribute("tUser", user);
        return JsonResult.success("修改成功");
    }

}
